package notification.test.com.notificationtest;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String ENABLED_NOTIFICATION_LISTENERS = "enabled_notification_listeners";
    private static final String ACTION_NOTIFICATION_LISTENER_SETTINGS = "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS";

    private static final int NOTIFICATION_SETTINGS_CODE = 101;

    private TextView text_desc;
    private String strItime;
    private NotificationManager mNotificationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn = (Button) findViewById(R.id.btn_start);
        Button btn_create_notification = (Button) findViewById(R.id.btn_create_notification);
        Button btn_cancel_notification = (Button) findViewById(R.id.btn_cancel_notification);
        btn.setOnClickListener(this);
        btn_create_notification.setOnClickListener(this);
        btn_cancel_notification.setOnClickListener(this);
        text_desc = (TextView) findViewById(R.id.text_desc);
        if (isEnableListen()) {
            text_desc.setText("已开启通知监听权限!");
        } else {
            text_desc.setText("未开启通知监听权限!");
        }
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        strItime = formatter.format(curDate);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_create_notification:
                createNotification();
                break;
            case R.id.btn_cancel_notification:
                cancelNotification();
                break;
            case R.id.btn_start:
                startListen();
                break;
        }
    }

    private void cancelNotification() {
        mNotificationManager.cancel(0);
    }

    private void createNotification() {
        CharSequence tickerText = getResources().getString(R.string.notification_content);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.qq_logo)
                .setContentTitle(getResources().getString(R.string.app_name));
        mBuilder.setTicker(tickerText);
        mBuilder.setContentText("这是ContentText");

        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.download_notification_layout);
        contentView.setTextViewText(R.id.update_title, getResources().getString(R.string.app_name));
        contentView.setTextViewText(R.id.update_pro, strItime);

        mBuilder.setContent(contentView);
        Notification mNotification = mBuilder.build();
        // 放置在"正在运行"栏目中
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;
        mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, mNotification);
    }

    private void startListen() {
        if (isEnableListen()) {
            startListenService();
        } else {
            startListenSettings();
        }
    }


    private void startListenService() {

        Intent intent = new Intent(this, MyNotificationListenerService.class);
        startService(intent);

        String text = text_desc.getText().toString();
        text += "\n已开启通知监听服务!";
        text += "\n正在监听通知消息...";
        text_desc.setText(text);
    }

    private void startListenSettings() {
        Intent intent = new Intent(ACTION_NOTIFICATION_LISTENER_SETTINGS);
        startActivityForResult(intent, NOTIFICATION_SETTINGS_CODE);
    }

    private boolean isEnableListen() {
        final String flat = Settings.Secure.getString(getContentResolver(),
                ENABLED_NOTIFICATION_LISTENERS);
        if (!TextUtils.isEmpty(flat)) {
            final String[] names = flat.split(":");
            for (int i = 0; i < names.length; i++) {
                final ComponentName cn = ComponentName.unflattenFromString(names[i]);
                if (cn != null) {
                    if (TextUtils.equals(getPackageName(), cn.getPackageName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == NOTIFICATION_SETTINGS_CODE) {
            startListen();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
